package res

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

type Response struct {
	Code int    `json:"code"`
	Data any    `json:"data"`
	Msg  string `json:"msg"`
}

var CodeMap = map[int]string{
	404: "请求路径不存在",
	403: "没有访问权限",
	400: "请求参数错误",
	401: "未登录",
	405: "请求方法错误",
	500: "服务器内部错误",
	501: "服务未实现",
	502: "网关错误",
}

func ResponseFunc(c *gin.Context, code int, data any, msg string) {
	c.JSON(http.StatusOK, &Response{
		Code: code,
		Msg:  msg,
		Data: data,
	})
}

func Ok(c *gin.Context, data any, msg string) {
	ResponseFunc(c, http.StatusOK, data, msg)
}
func OkWithMsg(c *gin.Context, msg string) {
	Ok(c, gin.H{}, msg)
}

func OkWithData(c *gin.Context, data any) {
	Ok(c, data, "操作成功")
}

func Fail(c *gin.Context, code int, msg string, data any) {
	ResponseFunc(c, code, data, msg)
}

func FailWithMsg(c *gin.Context, msg string) {
	Fail(c, http.StatusInternalServerError, msg, nil)
}

func FailWriteCode(c *gin.Context, code int) {
	msg, ok := CodeMap[code]
	if !ok {
		msg = "服务错误"
	}
	Fail(c, code, msg, nil)
}
